package cn.cjx.pet.controller;

import cn.cjx.basic.constant.LoginContext;
import cn.cjx.basic.exception.BusinessException;
import cn.cjx.org.domain.Employee;
import cn.cjx.org.service.IEmployeeService;
import cn.cjx.pet.service.IPetService;
import cn.cjx.pet.domain.Pet;
import cn.cjx.pet.query.PetQuery;
import cn.cjx.basic.utils.AjaxResult;
import cn.cjx.basic.utils.QueryResult;
import cn.cjx.pet.service.IPetTypeService;
import cn.cjx.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/pet")
public class PetController {
	@Autowired
	public IPetService petService;

	@Autowired
	private IEmployeeService employeeService;

	@PostMapping("/onsale")
	public AjaxResult onSale(@RequestBody List<Long> ids) {
		try {
			petService.onSale(ids);
			return AjaxResult.success();
		}catch (BusinessException e) {//我们自己的业务错误  自定义异常
			e.printStackTrace();
			return AjaxResult.error().setMessage(e.getMessage());
		}catch (Exception e) {//系统级别的错误
			e.printStackTrace();
			return AjaxResult.error();
		}
	}

	@PostMapping("/offsale")
	public AjaxResult offSale(@RequestBody List<Long> ids) {
		try {
			petService.offSale(ids);
			return AjaxResult.success();
		}catch (BusinessException e) {//我们自己的业务错误  自定义异常
			e.printStackTrace();
			return AjaxResult.error().setMessage(e.getMessage());
		}catch (Exception e) {//系统级别的错误
			e.printStackTrace();
			return AjaxResult.error();
		}
	}
	/**
	 * 保存和修改公用的
	 *
	 * @param pet 传递的实体
	 * @return Ajaxresult转换结果
	 */
	@PutMapping
	public AjaxResult addOrUpdate(@RequestBody Pet pet, HttpServletRequest request) {
		try {
			Logininfo logininfo = LoginContext.getLoginData(request);
			Employee employee = employeeService.loadByLogininfoId(logininfo.getId());
           	pet.setShopId(employee.getShopId());
			if (pet.getId() != null)
				petService.update(pet);
			else
				petService.save(pet);
			return AjaxResult.success();
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error();
		}
	}

	/**
	 * 删除对象信息
	 *
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/{id}")
	public AjaxResult delete(@PathVariable("id") Long id) {
		try {
			petService.remove(id);
			return AjaxResult.success();
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error();
		}
	}

	//获取用户
	@GetMapping("/{id}")
	public Pet get(@PathVariable("id") Long id) {
		return petService.loadById(id);
	}


	/**
	 * 查看所有的员工信息
	 *
	 * @return
	 */
	@GetMapping()
	public List<Pet> list() {

		return petService.loadAll();
	}


	/**
	 * 分页查询数据
	 *
	 * @param query 查询对象
	 * @return QueryResult 分页对象
	 */
	@PostMapping("/list")
	public QueryResult<Pet> json(@RequestBody PetQuery query) {
		return petService.queryPage(query);
	}
}
